var express = require('express');
var _ = require("underscore");
var Page = require('../models/page');
//codeState = boxSim.codeState;
var Box = require('../models/boxes');
var Buyer = require('../models/buyer');
var Sim = require('../models/sim');
var Log = require('../models/log');
var BoxBuyer = require('../models/box_buyer');
var User = require('../models/user');
var Category = require('../models/category');
var Goods = require('../models/goods');
var mqtt = require('mqtt');
var async=require('async');
var mongoose=require('mongoose');
var Billing=require('../models/billing');
var Fault = require('../models/fault');
var JPush=require('jpush-sdk')
require('date-utils');
var client = JPush.buildClient('861964de8ba89a2472881aad', '718ca3206d244f2b2c2ee09c');
//node.js 极光推送代码--推送所用
//client.push().setPlatform(JPush.ALL)
//    .setAudience(JPush.ALL)
//    .setNotification('Hi, JPush', JPush.ios('ios alert', 'happy', 5))
//    .send(function(err, res) {
//        if (err) {
//            console.log(err.message);
//        } else {
//            console.log('Sendno: ' + res.sendno);
//            console.log('Msg_id: ' + res.msg_id);
//        }
//    });

client.push().setPlatform('ios', 'android')
    .setAudience(JPush.registration_id('08046852d97'))
    .setNotification('用户，你好', JPush.ios('ios alert'), JPush.android('你有新的消息', null, 2))
    .setMessage('msg content')
    //.setOptions(null, 60)
    .send(function(err, res) {
        if (err) {
            console.log(err.message);
        } else {
            console.log('Sendno: ' + res.sendno);
            console.log('Msg_id: ' + res.msg_id);
        }
    });
module.exports=function(app) {
    app.get('/webapp/login', function (req, res) {

        var username = req.query.username;
        var password = req.query.password;
        new Buyer().findAccountByAccount(username, function (err, doc) {
            if (doc) {
                if (password != doc.password) {
                    res.send('1')
                } else {
                    console.log(doc)
                    req.session.webapp = doc;
                    //req.flash('success', '登陆成功.');
                    res.send('3')
                    //return res.redirect('/user_system?account='+username+'&&state=ok');
                }
            } else {
                res.send('2');
            }
        });
    })
    app.get('/webapp/boxs', function (req, res) {

        console.log(req.session.webapp)
        new Buyer().findAccountByAccount(req.session.webapp.account,function(err,doc){
            req.session.buyer_id=doc.buyer_id;
            var buyer_id=doc.buyer_id;
            new BoxBuyer().findIdsByBuyer(buyer_id,function(datas) {
                if (datas.length > 0) {
                    var boxes=[];
                    for(var i=0;i<datas.length;i++){
                        boxes.push(datas[i].box_id);
                    }
                    var options={box_id:{$in:boxes}};
                    var page = new Page(req.query.num);
                    var obj = {
                        page: page,
                        search: options
                    };
                    console.log(boxes);
                    new Box().findForPage(obj, function (err, count, pageCount, datas) {
                        if(datas.length==0){
                            page.pageCount=1;
                            var final={
                                datas:[],
                                page:page
                            }
                            res.send(final)
                        }else{
                            page.pageCount = pageCount;
                            var final={
                                datas:datas,
                                page:page
                            }
                            res.send(final);
                        }

                    });
                }else{
                    var page={
                        num:1,
                        pageCount:1
                    }
                    var final={
                        datas:[],
                        page:page
                    }
                    res.send(final)
                }
            });
        });
    })
    //购买人箱子详情页面
    app.get('/webapp/box',function(req,res){
        var boxid=req.query.box_id;
        var buyerid=req.session.buyer_id;
        console.log(buyerid)
        new Box().findBoxById(boxid,function(datas){
            var boxDatas=datas;
            new Sim().findSimById(boxid,function(datas){
                var simDatas=datas;
                new Buyer().findById(buyerid,function(datas){
                    var buyerdatas=datas;
                    var final={
                        simdatas:simDatas,
                        boxDatas:boxDatas[0],
                        buyerdatas:buyerdatas
                    }
                    console.log(final)
                    res.send(final);
                });
            });
        });
    });
    //设置计费页面
    app.get('/webapp/cost',function(req,res){
        var boxid=req.query.box_id;
        new Billing().findSpriceById(boxid,function(datas){
            console.log(datas)
            res.send(datas[0]?datas[0]:{
                standard:'',
                price: '',
                less: '',
                lessprice:'',
                more:'',
                moreprice:''
            })
        });
    });
    app.post('/webapp/cost',function(req,res){
        var box_id=req.body.box_id;
        console.log(box_id)
        var account=req.session.webapp.account;
        var standard = req.body.standard;
        var timetype = req.body.timetype;
        var price = req.body.price;
        var less = req.body.less;
        var lesstimetype = req.body.lesstimetype;
        var lessprice = req.body.lessprice;
        var more = req.body.more;
        var moretimetype = req.body.moretimetype;
        var moreprice = req.body.moreprice;

        new Billing().removepriceById(box_id,function(err){
            new Billing({
                box_id: box_id,
                standard:standard*timetype,
                price: price,
                less: less*lesstimetype,
                lessprice:lessprice,
                more:more*moretimetype,
                moreprice:moreprice
            }).save(function(err){
                 res.send('1')
            });
        });

    });
    //用户门状态页面
    app.get('/webapp/doorState',function(req,res){
        var boxid=req.query.box_id;
        var index=req.query.index;
        if(index==0) {
            new Box().findByBoxId2(boxid, function (data) {
                var final={
                    doors:data.doors,
                    layout:data.layout
                }
                res.send(final)
            });
        }else if(index=="all"){
            var doorsnum=req.query.doorsnum;
            var doors = [];
            async.waterfall([
                function(callback){
                    new Box().findByBoxId2(boxid,function(data) {
                        callback(null,data)
                    });
                },
                function(data,callback){
                    var count = 0;
                    async.whilst(
                        function () { return count < data.doors_num; },
                        function (callback) {
                            new Box().updateByBoxidAndIndex(boxid, count+1,function(){

                            });
                            if(!data.doors[count].empty){
                                console.log('已进入')
                                if(data.doors[count].gid){
                                    new Goods().updById(data.doors[count].gid._id,{'$inc':{sellNum:-1,num:1}},function(){
                                        count++;
                                        callback(null);
                                    })
                                }
                            }else{
                                count++;
                                callback(null);
                            }

                        },
                        function (err) {
                            console.log(count)
                            callback();
                        }
                    );
                }
            ], function (err) {
                res.send('')
            });

        }else{
            if(req.query.gid){
                new Goods().updById(req.query.gid,{'$inc':{sellNum:-1,num:1}},function(){

                })
            }
            new Box().updateByBoxidAndIndex(boxid, index,function(data){
                res.send('')
            });
        }
    });
    app.get('/webapp/useSet',function(req,res){
        var boxid=req.query.box_id;
        var index=req.query.index;
        var use=req.query.use;
        console.log(boxid+'---'+index+'----'+use)
        new Box().updateDoorUse(boxid,index,use,function(){
            res.send('')
        })
    });
    app.post('/webapp/addr',function(req,res){
        var boxid=req.body.box_id;
        var addr=req.body.addr
        var lng=req.body.lng;
        var lat=req.body.lat;
        var addrDescribe=req.body.addrDescribe
        console.log(boxid+'---'+addr+'---'+lng+'---'+lat)
        var options ={addr:addr,lng:lng,lat:lat,addrDescribe:addrDescribe}
        new Box().updateAddr(boxid,options,function(){
            res.send('')
        })
    });
    app.get('/webapp/fault',function(req,res){

        var account=req.session.webapp.account;
        new Buyer().findAccountByAccount(account,function(err,doc){
            var buyer_id=doc.buyer_id;
            new BoxBuyer().findIdsByBuyer(buyer_id,function(datas) {
                if (datas.length >0) {
                    var boxes=[];
                    for(var i=0;i<datas.length;i++){
                        boxes.push(datas[i].box_id);
                    }
                    var options={box_id:{$in:boxes}};
                    new Sim().findUserSimById(options,function(err,datas){
                        var sims=[];
                        for(var i=0;i<datas.length;i++){
                            sims.push(datas[i].sim);
                        }
                        var page = new Page(req.query.num);
                        var obj = {
                            page: page,
                            search: {sim:{$in:sims}}
                        };
                        new Fault().findForPage(obj,function(err, count, pageCount, faultDatas) {
                            if (err) {
                                console.log("faultM-----" + err);
                            }
                            for(var i=0;i<faultDatas.length;i++){
                                faultDatas[i]._doc.faultDate=(faultDatas[i].date).toFormat('YYYY-MM-DD HH24:MI:SS')
                            }
                            if(faultDatas.length==0){
                                page.pageCount=1;
                                var final={
                                    datas:[],
                                    page:page
                                }
                                res.send(final)
                            }else{
                                page.pageCount = pageCount;
                                var final={
                                    datas:faultDatas,
                                    page:page
                                }
                                res.send(final)
                            }

                        })
                    });

                }else{
                    var page={
                        num:1,
                        pageCount:1
                    }
                    var final={
                        datas:[],
                        page:page
                    }
                    res.send(final)
                }
            });
        });
    });
    app.get('/webapp/category',function(req,res){
//        Category.remove({},function(err){
//
//        })
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {account:req.session.webapp.account}
        };
        new Category().findForPage(obj,function(err, count, pageCount,datas){
            if(datas.length==0){
                page.pageCount=1;
                var final={
                    datas:[],
                    page:page
                }
                res.send(final)
            }else{
                page.pageCount = pageCount;
                var final={
                    datas:datas,
                    page:page
                }
                res.send(final)
            }

        })

    });
    app.post('/webapp/addCategory',function(req,res){
        var name=req.body.name;
        new Category({
            name:name,
            account:req.session.webapp.account
        }).save(function(err){
            res.send('1')
        })

    });
    app.get('/webapp/delCategory',function(req,res){
        var id=req.query.id;
        new Category().delById(id,function(err){
            res.send('1')
        })

    });
    app.get('/webapp/showGoods',function(req,res){
        var id=req.query.gid;
        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {category:id}
        };

        new Goods().findForPage(obj,function(err, count, pageCount,datas){
            if(datas.length==0){
                page.pageCount=1;
                var final={
                    datas:[],
                    page:page
                }
                res.send(final)
            }else{
                page.pageCount = pageCount;
                var final={
                    datas:datas,
                    page:page
                }
                res.send(final)
            }
        })

    });
    app.post('/webapp/updCategory',function(req,res){
        var id=req.query.id;
        var opt={name:req.body.name}
        res.send('')
        new Category().updById(id,opt,function(err){
            res.send('1')
        })

    });
    app.post('/webapp/uploadImg',function(req,res){
            console.log(req.files)
            //fs.rename(req.files.file.path,'public/images/test/'+req.files.file.name);
            var word=req.files.file.path.replace('public','');
            req.session.webapp.img=word;
            res.send(word);
    })
    app.post('/webapp/addGoods',function(req,res){
        new Category().updateNumberById(req.body.gid,1,function(err){
            new Goods({
                sort:req.body.sort,
                name:req.body.name,
                attr:req.body.attr,
                price:req.body.price,
                num:req.body.num,
                category:req.body.gid,
                imgData:req.body.imgData
            }).save(function(err){
                    res.send('')
                })
        })

    })
    app.get('/webapp/goodsPar',function(req,res){
        var id=req.query.id;
        new Goods().findByGoodsById(id,function(data){
            res.send(data)
        })

    });
    app.get('/webapp/delGoods',function(req,res){
        var id=req.query.id;
        var gid=req.query.gid;

        new Category().updateNumberById(gid,-1,function(err){
            if(!err){
                new Goods().delById(id,function(){
                    res.send('')
                })
            }
            res.send('')

        })



    });
    app.post('/webapp/changGoods',function(req,res){
        console.log(req.body._id)
        var opt={
            sort:req.body.sort,
            name:req.body.name,
            attr:req.body.attr,
            price:req.body.price,
            imgData:req.body.imgData
        }
        new Goods().updById(req.body._id,opt,function(err){
                res.send('')
        })

    })
    app.get('/webapp/changPassword',function(req,res){
        var password=req.query.password;
        new Buyer().updatePwd(req.session.webapp.account,password,function(err){
            res.send('');
        })
    })
    app.post('/webapp/sellGoods',function(req,res){
        var gid=req.body.gid
        var boxDatas=req.body.boxDatas
        var opt1={
            'box_id':boxDatas.box_id,
            'doors.index':boxDatas.doorDatas.index
        }
        var opt2={
            'doors.$.empty': false,
            'doors.$.gid':gid
        }
        new Box().updateOpt(opt1,opt2,function(err){
            if(!boxDatas.doorDatas.empty){
                if(boxDatas.doorDatas.gid._id){
                    new Goods().updById(boxDatas.doorDatas.gid._id,{'$inc':{sellNum:-1,num:1}},function(){

                    })
                }
            }

            new Goods().updById(gid,{'$inc':{sellNum:1,num:-1}},function(err){
                new Box().findByBoxId2(boxDatas.box_id,function(data){
                    var param={
                        box_id:data.box_id,
                        doorDatas:data.doors[boxDatas.doorDatas.index-1]
                    }
                    res.send(param)
                })
            })

        })
    })
    app.post('/webapp/cancelSell',function(req,res){
        var box_id=req.body.box_id
        var index=req.body.doorDatas.index
        var gid=req.body.doorDatas.gid._id
        var opt1={
            'box_id':box_id,
            'doors.index':index
        }
        var opt2={
            'doors.$.empty':true
        }
        new Box().updateOpt(opt1,opt2,function(err,result){
            console.log(err)
            new Goods().updById(gid,{'$inc':{sellNum:-1,num:1}},function(err){
                new Box().findByBoxId2(box_id,function(data){
                    var param={
                        box_id:data.box_id,
                        doorDatas:data.doors[index-1]
                    }
                    console.log(param)
                    res.send(param)
                })
            })
        })
    })
    app.get('/webapp/sellPar', function (req, res) {
        var id=req.query.id

        console.log(req.session.webapp)
        new Buyer().findAccountByAccount(req.session.webapp.account,function(err,doc){
            req.session.buyer_id=doc.buyer_id;
            var buyer_id=doc.buyer_id;
            new BoxBuyer().findIdsByBuyer(buyer_id,function(datas) {
                if (datas.length > 0) {
                    var boxes=[];
                    for(var i=0;i<datas.length;i++){
                        boxes.push(datas[i].box_id);
                    }
                    var options={box_id:{$in:boxes},'doors.gid':id,'doors.empty':false};
                    var page = new Page(req.query.num);
                    var obj = {
                        page: page,
                        search: options
                    };
                    console.log(boxes);
                    new Box().findForPage(obj, function (err, count, pageCount, datas) {
                        if(datas.length==0){
                            page.pageCount=1;
                            var final={
                                datas:[],
                                page:page
                            }
                            res.send(final)
                        }else{
                            page.pageCount = pageCount;
                            var final={
                                datas:datas,
                                page:page
                            }
                            res.send(final);
                        }

                    });
                }else{
                    var page={
                        num:1,
                        pageCount:1
                    }
                    var final={
                        datas:[],
                        page:page
                    }
                    res.send(final)
                }
            });
        });
    })
//    app.get('/webapp/uploadImg',function(req,res){
//       req.session.webapp.imgDatas=req.query.imgDatas;
//       res.send('');
//    })


}